package com.loveofsoftware.fotolab;

import java.io.File;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;

public class Util {
	public static String getNewName(String originalName, Context ctx) {
		if(null == originalName)
		{
			originalName = "tmp";
			System.out.println("ERROR: Why did i get null orginalName?");
		}
        int MAX_ATTEMPTS = 10;
        int attempts = 0;
        
        String result = getFotolabDir(ctx);// + Constants.APP_NAME + "/";
        while(attempts++ < MAX_ATTEMPTS) {
              String picName = originalName.substring(originalName.lastIndexOf("/")+1);
              //remove the extension such as .jpg, .png etc
              picName = picName.replaceAll("\\..*", "");
              
              picName = result + picName + System.currentTimeMillis() + ".png";
              
              File file = new File(picName);
              if(!file.exists())
                    return picName;
        }
        
        throw new RuntimeException("couldn't get a name");
  }
	
	private static void alert(String msg, Context ctx)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
		builder.setMessage(msg)
		       .setCancelable(false)
		       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		               
		           }
		       })		       
		       ;
		AlertDialog alert = builder.create();
		alert.show();
	}
	public static String getFotolabDir(Context ctx)
	{
		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
		    // We can read and write the media
		    mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
		    // We can only read the media
		    mExternalStorageAvailable = true;
		    mExternalStorageWriteable = false;
		} else {
		    // Something else is wrong. It may be one of many other states, but all we need
		    //  to know is we can neither read nor write
		    mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		
		if(!mExternalStorageAvailable)
		{
			alert("External media is not available. App may not function correctly",ctx);
		}else if(!mExternalStorageWriteable)
		{
			alert("External media is not writable. App may not function correctly",ctx);
		}
		return Environment.getExternalStorageDirectory().getAbsolutePath()+"/fotolab/";
		
	}


}
